package com.halotis.taskLauncher.engine;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import com.halotis.taskLauncher.CommandRule;
import com.halotis.taskLauncher.CommandRules;
import com.halotis.taskLauncher.im.IMClient;

public class Command implements Runnable {

	private String imUser;
	private String request;
	
	public Command(String user, String cmd){
		imUser = user;
		request = cmd;
	}

	public void run() {
		try{
			
			String line;
			StringBuffer result = new StringBuffer();
            
            for(CommandRule rule : CommandRules.getInstance()){
            	if(rule.matches(request)){
            		
                    String cmd = String.format(rule.getCommand(), request);
        			Process p = Runtime.getRuntime().exec(cmd);
        			BufferedReader  input = new BufferedReader(new InputStreamReader(p.getInputStream()));
        			while ((line = input.readLine()) != null){
        				result.append(line+"\n");
        			}
        			input.close();
        			//p.waitFor();
        			
        			returnResults(result.toString());
                    
        			break;
            	}
            }
		
		} catch (Exception err){
			err.printStackTrace();
		}
	}
	
	private void returnResults(String result) throws Exception {
		IMClient.sendMessage(imUser, result);
	}
		
}
